<?php
/**
 * Created by PhpStorm.
 * User: LiuTao
 * Date: 2018/11/12
 * Time: 16:36
 */

class UdpClient
{

    protected $addr = '127.0.0.1';
    protected $port = 10000;

    public function start()
    {
        if (($socket = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP)) == FALSE) {
            $errorcode = socket_last_error();
            $errormsg = socket_strerror($errorcode);
            $this->error("创建socekt失败: [$errorcode] $errormsg");
        }
        $this->info('socket 创建成功...');
        while (true) {
            $input = $this->read();
            if (!socket_sendto($socket, $input, strlen($input), 0, $this->addr, $this->port)) {
                $errorcode = socket_last_error();
                $errormsg = socket_strerror($errorcode);
                $this->error("Could not send data: [$errorcode] $errormsg \n");
            }

            // UDP 是一种无链接的传输层协议, 不需要也无法获取返回消息
        }
        socket_close($socket);
    }

    /**
     * 终端给提示获取用户数据
     *
     * @param string $str
     * @return string
     */
    protected function read($str = '请输入')
    {
        //提示输入
        fwrite(STDOUT, $str . ":");
        //获取用户输入数据
        $result = trim(fgets(STDIN));
        return trim($result);
    }

    protected function info($msg)
    {
        echo $msg . PHP_EOL;
    }

    protected function error($msg)
    {
        echo $msg . PHP_EOL;
        exit();
    }
}

$client = new UdpClient();
$client->start();